using AutoMapper;
using BaseData.CommonLib.Models;
using BaseData.DomainLib.AggregatesModel.SupplierAggregate;
using MediatR;
using Swimj.CommonLib.Base;

namespace BaseData.ApplicationLib.Commands
{
    public class UpdateSupplierCommand : SupplierEditRequestDto, IRequest<Result<SupplierInfoResponseDto>>
    {
        public int Id { get; set; }
    }

    
    public class UpdateSupplierCommandHandler : IRequestHandler<UpdateSupplierCommand, Result<SupplierInfoResponseDto>>
    {

        private readonly ISupplierRepository _supplierRepository;
        private readonly IMapper _mapper;

        public UpdateSupplierCommandHandler(ISupplierRepository supplierRepository,
        IMapper mapper)
        {
            this._supplierRepository = supplierRepository;
            this._mapper = mapper;
        }

        public async Task<Result<SupplierInfoResponseDto>> Handle(UpdateSupplierCommand request, CancellationToken cancellationToken)
        {
            var supplier = await _supplierRepository.Get(request.Id);
            supplier?.Update(request.Name, request.Phone, request.Email, request.Address, request.Description);

            await _supplierRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return await Result<SupplierInfoResponseDto>.SuccessAsync(_mapper.Map<SupplierInfoResponseDto>(supplier));
        }
    }
}